package com.py.credit.controller;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.enums.CreditMapFieldEnum;
import com.py.credit.service.CreditMapService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * 异议处理controller
 */
@RestController
@RequestMapping(value = "/creditMap")
public class CreditMapController {

    private final static String FRONT_TABLE_ID = "creditMap";

    @Autowired
    private CreditMapService creditMapService;

    @Autowired
    private RemoteBaseService remoteBaseService;

    @Value("${absolutepath}")
    private String absolutepath;

    /**
     * 天地图调用字典值
     */
    private static String TDMAP = "TDMAP";
    /**
     * 天地图调用URL
     */
    private static String TDURL = "URL";
    /**
     * 天地图调用KEY
     */
    private static String TDKEY = "KEY";

    /**
     * @api {get} /dataQuality/export.json 数据质量报告导出
     * @apiName export
     * @apiVersion 0.0.1
     * @apiGroup 数据质量报告
     * @apiParam {String} condition 查询条件
     * @apiParam {String} columnEN 列英文名
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     */
    @ResponseBody
    @RequestMapping(value = "/export.json")
    public RestServiceResult<Object> export(HttpServletRequest request, HttpServletResponse response,
                                            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, String type,
                                            String search, String sbnf, String qyid,
                                            @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page) {
        RestServiceResult<Object> result = new RestServiceResult<>();
        if (sbnf != null && sbnf.equals("1")) {
            Calendar date = Calendar.getInstance();
            sbnf = String.valueOf((Integer) date.get(Calendar.YEAR));
        }
        if (columnEN == null || columnEN.equals("")) {
            columnEN = "[\"A000001\",\"A000002\",\"A000003\",\"A000004\",\"A000005\",\"A000006\"]";
        }
        page.setLimit(100000000);
        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
        try {
            List<Map<String, Object>> data = creditMapService.creditMapListByConditionForPage(showColumns, null,
                    condition, page, type, search, sbnf, qyid);
            result.setCount(page.getTotalCount());
            result.setData(data);
            ExcelUtil.downloadExcel(response, data, "信用地图", "信用地图", showColumns,
                    CreditMapFieldEnum.getOptionalColumns());
            return result;
        } catch (Exception e) {
            ExceptionLogger.error("CreditMapController#export", "信用地图导出异常！ERROR:" + e.getMessage(), e);
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("信用地图导出异常！");
            return result;
        }
    }

    /**
     * 查询企业列表页面
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/queryAllAreaCodes.json")
    public RestServiceResult<List<Map>> queryAllAreaCodes(HttpServletRequest request) {
        RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("DissentInfoController#getList", "未获取到当前用户信息！");
                return result;
            }

            result.setData(creditMapService.queryAllAreaCodes());
            return result;
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;

        }
    }

    /**
     * 查询企业列表页面
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/getLonAndLatByQybm.json")
    public RestServiceResult<Map> getLonAndLatByQybm(HttpServletRequest request, String qybm) {
        RestServiceResult<Map> result = new RestServiceResult<Map>();

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("DissentInfoController#getList", "未获取到当前用户信息！");
                return result;
            }

            result.setData(creditMapService.getLonAndLatByQybm(qybm));
            return result;
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;

        }
    }

    /**
     * @api {get} /creditMap/updateLonAndLat.json 经纬度更新定时任务
     * @apiName updateLonAndLat
     * @apiVersion 0.0.1
     * @apiGroup 经纬度更新
     */
    @RequestMapping(value = "/updateLonAndLat.do")
    public RestServiceResult<Object> updateLonAndLat() {
        try {
            String mapUrl = remoteBaseService.getDictByDtlKey(TDMAP, TDURL).getData().getDtlValue();
            String mapKey = remoteBaseService.getDictByDtlKey(TDMAP, TDKEY).getData().getDtlValue();
            creditMapService.updateLonAndLat(mapUrl, mapKey);
            return new RestServiceResult<>();
        } catch (Exception e) {
            RestServiceResult<Object> result = new RestServiceResult<Object>();
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("经纬度更新定时任务异常！ERROR:" + e.getMessage());
            ExceptionLogger.error("经纬度更新定时任务DataRemindController#taskRemind", "任务提醒定时任务异常！ERROR:" + e.getMessage(), e);
            return result;
        }
    }

    /**
     * @api {get} /creditMap/initAreaMap.json 区域汇总数据初始化定时任务
     * @apiName initAreaMap
     * @apiVersion 0.0.1
     * @apiGroup 经纬度更新区域汇总数据初始化
     */
    @RequestMapping(value = "/initAreaMap.do")
    public RestServiceResult<Object> initAreaMap() {
        try {
            creditMapService.initAreaMap();
            return new RestServiceResult<Object>();
        } catch (Exception e) {
            RestServiceResult<Object> result = new RestServiceResult<Object>();
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("任务提醒定时任务异常！ERROR:" + e.getMessage());
            ExceptionLogger.error("任务提醒定时任务DataRemindController#taskRemind", "任务提醒定时任务异常！ERROR:" + e.getMessage(), e);
            return result;
        }
    }

    /**
     * @api {get} /creditMap/initDeptMap.json 部门汇总数据初始化定时任务
     * @apiName initDeptMap
     * @apiVersion 0.0.1
     * @apiGroup 部门汇总数据初始化
     */
    @RequestMapping(value = "/initDeptMap.do")
    public RestServiceResult<Object> initDeptMap() {
        try {
            creditMapService.initDeptMap();
            return new RestServiceResult<Object>();
        } catch (Exception e) {
            RestServiceResult<Object> result = new RestServiceResult<Object>();
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("任务提醒定时任务异常！ERROR:" + e.getMessage());
            ExceptionLogger.error("任务提醒定时任务DataRemindController#taskRemind", "任务提醒定时任务异常！ERROR:" + e.getMessage(), e);
            return result;
        }
    }

    /**
     * 查询企业列表页面
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/queryListBasicMap.json")
    public RestServiceResult<List<Map>> queryListBasicMap(HttpServletRequest request, String type, String search,
                                                          String sbnf, String qyid) {
        if (sbnf != null && sbnf.equals("1")) {
            Calendar date = Calendar.getInstance();
            sbnf = String.valueOf((Integer) date.get(Calendar.YEAR));
        }
        // creditMapService.updateLonAndLat(mapUrl);
        // creditMapService.initAreaMap();
        // creditMapService.initDeptMap();
        RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("DissentInfoController#getList", "未获取到当前用户信息！");
                return result;
            }

            result.setData(creditMapService.queryListBasicMap(type, search, sbnf, qyid));
            return result;
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;

        }
    }

    /**
     * 查询企业列表页面
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/queryMapAreaList.json")
    public RestServiceResult<List<Map>> queryMapAreaList(HttpServletRequest request, String qyid, String sbnf) {
        RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
        if (sbnf != null && sbnf.equals("1")) {
            Calendar date = Calendar.getInstance();
            sbnf = String.valueOf((Integer) date.get(Calendar.YEAR));
        }
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("DissentInfoController#getList", "未获取到当前用户信息！");
                return result;
            }

            result.setData(creditMapService.queryMapAreaList(qyid, sbnf));
            return result;
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;

        }
    }

    /**
     * 查询企业列表页面
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/queryMapDeptList.json")
    public RestServiceResult<List<Map>> queryMapDeptList(HttpServletRequest request, String qyid, String sbnf) {
        RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
        if (sbnf != null && sbnf.equals("1")) {
            Calendar date = Calendar.getInstance();
            sbnf = String.valueOf((Integer) date.get(Calendar.YEAR));
        }
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("DissentInfoController#getList", "未获取到当前用户信息！");
                return result;
            }

            result.setData(creditMapService.queryMapDeptList(qyid, sbnf));
            return result;
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;

        }
    }

    /**
     * 查询企业列表页面
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/querySingleBasicInfBytybm.json")
    public RestServiceResult<Map> querySingleBasicInfBytybm(HttpServletRequest request, String tybm) {
        RestServiceResult<Map> result = new RestServiceResult<Map>();

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("DissentInfoController#getList", "未获取到当前用户信息！");
                return result;
            }

            result.setData(creditMapService.querySingleBasicInfBytybm(tybm));
            return result;
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;

        }
    }

}